package com.zhihaoliang.coroutine.buss.excep.func

import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.*
import java.io.IOException

/**
 * @author 支豪亮
 * @date 2022/10/28 16:14
 * @des 异常聚合
 */
object AggregationException {
    @OptIn(DelicateCoroutinesApi::class)
    fun exceptionAggregationNormal(mainScope: CoroutineScope) = mainScope.launch {
        val handler = CoroutineExceptionHandler { _, exception ->
            log(
                "CoroutineExceptionHandler got $exception with suppressed ${exception.suppressed.contentToString()}")
        }
        val job = GlobalScope.launch(handler) {
            launch {
                try {
                    delay(Long.MAX_VALUE) // 当另一个同级的协程因 IOException  失败时，它将被取消
                } finally {
                    throw ArithmeticException() // 第二个异常
                }
            }
            launch {
                delay(100)
                throw IOException() // 首个异常
            }
            delay(Long.MAX_VALUE)
        }
        job.join()
    }

    @OptIn(DelicateCoroutinesApi::class)
    fun exceptionAggregationCancel(mainScope: CoroutineScope) = mainScope.launch {
        val handler = CoroutineExceptionHandler { _, exception ->
            log(
                "CoroutineExceptionHandler got $exception with suppressed ${exception.suppressed.contentToString()}")
        }
        val job = GlobalScope.launch(handler) {
            val inner = launch { // 该栈内的协程都将被取消
                launch {
                    launch {
                        throw IOException() // 原始异常
                    }
                }
            }
            try {
                inner.join()
            } catch (e: CancellationException) {
                log("Rethrowing CancellationException with original cause")
                throw e // 取消异常被重新抛出，但原始 IOException 得到了处理
            }
        }
        job.join()
    }
}